package com.taptech.doufu.util;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.widget.Toast;

import com.google.gson.Gson;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.bean.ExtraBean;
import com.taptech.doufu.services.DownloadWcsApkService;
import com.taptech.doufu.listener.ICallbackResult;


import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/8/26.
 */
public class AppUtil2
{
    public static void openApp(Context context, String packageName)
    {
//        PackageManager pm = context.getPackageManager();
//        PackageInfo pi = null;
//        try
//        {
//            pi = pm.getPackageInfo(packageName, 0);
//        } catch (PackageManager.NameNotFoundException e)
//        {
//            e.printStackTrace();
//        }
//        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
//        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//        resolveIntent.setPackage(pi.packageName);
//
//        List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);
//
//        ResolveInfo ri = apps.iterator().next();
//        if (ri != null)
//        {
//            TMAnalysis.event(context, "open_apk", "packageName", packageName.replace(".", "_"));
//            String package_Name = ri.activityInfo.packageName;
//            String className = ri.activityInfo.name;
//
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.addCategory(Intent.CATEGORY_LAUNCHER);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            ComponentName cn = new ComponentName(package_Name, className);
//
//            intent.setComponent(cn);
//            context.startActivity(intent);
//        }
    }

    private static List<String> appList = new ArrayList<String>();

    public static void addAppList(String packageName)
    {
        if (appList == null)
        {
            appList = new ArrayList<String>();
        }
        if (!appList.contains(packageName))
        {
            appList.add(packageName);
        }
    }

    public static List<String> getAppList()
    {
        return appList;
    }

    public static boolean isApplicationAvilible(Context context, String packageName)
    {
//        final PackageManager packageManager = context.getPackageManager();
//        // 获取所有已安装程序的包信息
//        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
//        for (int i = 0; i < pinfo.size(); i++)
//        {
//            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
//                return true;
//        }
        return false;
    }

    private static DownloadWcsApkService.DownloadBinder binder;
    private static boolean isBinded = false;
    private static Context context;
    private static ICallbackResult callback = new ICallbackResult()
    {
        @Override
        public void OnBackResult(Object result)
        {
            if ("finish".equals(result))
            {
                ((Activity) context).finish();
                return;
            }
        }
    };
    static ServiceConnection conn = new ServiceConnection()
    {
        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            isBinded = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            binder = (DownloadWcsApkService.DownloadBinder) service;
            // System.out.println("服务启动!!!");
            // 开始下载
        /*    binder = (DownloadWcsApkService.DownloadBinder) service;
            System.out.println("服务启动!!!");
            // 开始下载*/
            isBinded = true;
            binder.addCallback(callback);
            binder.start();
        }

    };


    public static void downLoadApp(final Context mcontext, final ExtraBean extraBean)
    {
     /*   Intent intent = new Intent(context, ActDownload.class);
        // Intent intent = new Intent(SquareActivity.this, TestActicity.class);
        intent.putExtra(Constant.DATA, extraBean);
        context.startActivity(intent);*/
        if (extraBean != null && extraBean.getPkg_name() != null)
        {
            addAppList(extraBean.getPkg_name());
        }
        int netType = NetworkInfoUtil.getNetworkType();
        if (netType == NetworkInfoUtil.NET_TYPE_OFF_LINE)
        {
            Toast.makeText(mcontext, "当前无网络，请检查你的网络设置！", Toast.LENGTH_SHORT);
        } else if (netType == NetworkInfoUtil.NET_TYPE_WIFI)
        {
            Toast.makeText(mcontext, "已开始下载！", Toast.LENGTH_SHORT).show();
            TMAnalysis.event(context, "download_apk", "packageName", extraBean.getPkg_name().replace(".", "_"));
            goDownLoadApp(mcontext, extraBean);
        } else
        {
            UIUtil.showEnsureDialog((Activity) mcontext, "非WIFI情况下下载将消耗流量，是否继续下载？", new UIUtil.EnsureListener()
            {
                @Override
                public void sure()
                {
                    goDownLoadApp(mcontext, extraBean);
                }

                @Override
                public void cancel()
                {
                }
            });
        }
    }

    public static void goDownLoadApp(Context mcontext, ExtraBean extraBean)
    {
        context = mcontext;
        Intent intentDownload = new Intent(context, DownloadWcsApkService.class);
        intentDownload.putExtra(Constant.DATA, extraBean);
        context.startService(intentDownload);
        context.bindService(intentDownload, conn, Context.BIND_AUTO_CREATE);
    }

    public static ExtraBean getExtreFromJsonObj(JSONObject extrasJson)
    {
        ExtraBean extraBean = new ExtraBean();
        if (extrasJson != null)
        {
            try
            {
                if (extrasJson.has("dl_url"))
                {
                    extraBean.setPkg_name(extrasJson.getString("dl_url"));
                }
                if (extrasJson.has("pkg_name"))
                {
                    extraBean.setPkg_name(extrasJson.getString("pkg_name"));
                }
                if (extrasJson.has("sha1"))
                {
                    extraBean.setPkg_name(extrasJson.getString("sha1"));
                }
                if (extrasJson.has("size"))
                {
                    extraBean.setPkg_name(extrasJson.getString("size"));
                }

            } catch (Exception e)
            {
            }

        }
        return extraBean;
    }

    public static ExtraBean getExtreFromJsonObj(String extraString_temp)
    {
        ExtraBean extraBean = new ExtraBean();
        if (extraString_temp != null)
        {
            // TTLog.i("TAG", "extraString_temp:" + extraString_temp);
            String extraString = extraString_temp.replace("{", "").replace("}", "").replace("\'", "").replace("\"", "");
            String extraStrings[] = extraString.split(",");
            try
            {
                for (int i = 0; i < extraStrings.length; i++)
                {
                    if (extraStrings[i].contains("dl_url:"))
                    {
                        extraBean.setDl_url(extraStrings[i].replace("dl_url:", "").trim());
                        continue;
                    }
                    if (extraStrings[i].contains("sha1:"))
                    {
                        extraBean.setSha1(extraStrings[i].replace("sha1:", "").trim());
                        continue;
                    }
                    if (extraStrings[i].contains("size:"))
                    {
                        extraBean.setSize(extraStrings[i].replace("size:", "").trim());
                        continue;
                    }
                    if (extraStrings[i].contains("pkg_name:"))
                    {
                        extraBean.setPkg_name(extraStrings[i].replace("pkg_name:", "").trim());
                        continue;
                    }

                }

            } catch (Exception e)
            {
            }

        }
        return extraBean;
    }

    public static ExtraBean stringConvertToObject(String extraString_temp)
    {
        Gson gson = new Gson();
        ExtraBean extraBean = gson.fromJson(extraString_temp, ExtraBean.class);
        // List<AlbumsBean> dataList = DiaobaoUtil.(AlbumsBean.class, data.getJSONArray("albums"));
        return extraBean;
    }

    public static ExtraBean getExtreFromJsonObj_old(String extraString_temp)
    {
        ExtraBean extraBean = new ExtraBean();
        if (extraString_temp != null)
        {
            TTLog.i("TAG", "extraString_temp:" + extraString_temp);
            String extraString = extraString_temp.replace("{", "").replace("}", "").replace("\'", "").replace("\"", "").replace("dl_url:", "").replace("sha1:", "").replace("size:", "").replace("pkg_name:", "");
            String extraStrings[] = extraString.split(",");
            TTLog.i("TAG", "extraString111:" + extraString);
            try
            {
                extraBean.setDl_url(extraStrings[0].trim());
                extraBean.setSha1(extraStrings[1].trim());
                extraBean.setSize(extraStrings[2].trim());
                extraBean.setPkg_name(extraStrings[3].trim());


               /* if (extraStrings[0].replace("dl_url:", "").trim() != null)
                {
                    extraBean.setPkg_name(extraStrings[0].replace("dl_url:", "").trim());
                }
                if (extraStrings[1].replace("sha1:", "").trim() != null)
                {
                    extraBean.setPkg_name(extraStrings[1].replace("sha1:", "").trim());
                }
                if (extraStrings[2].replace("size:", "").trim() != null)
                {
                    extraBean.setPkg_name(extraStrings[2].replace("size:", "").trim());
                }
                if (extraStrings[3].replace("pkg_name:", "").trim() != null)
                {
                    extraBean.setPkg_name(extraStrings[3].replace("pkg_name:", "").trim());
                }
*/
            } catch (Exception e)
            {
            }

        }
        return extraBean;
    }

    /**
     * 适用于上G大的文件
     */
  /*  public static String getFileSha1(String path) throws OutOfMemoryError, IOException
    {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        MessageDigest messagedigest;
        try
        {
            messagedigest = MessageDigest.getInstance("SHA-1");

            byte[] buffer = new byte[1024 * 1024 * 10];
            int len = 0;

            while ((len = in.read(buffer)) > 0)
            {
                //该对象通过使用 update（）方法处理数据
                messagedigest.update(buffer, 0, len);
            }

            //对于给定数量的更新数据，digest 方法只能被调用一次。在调用 digest 之后，MessageDigest 对象被重新设置成其初始状态。
            return byte2hex(messagedigest.digest());
        } catch (NoSuchAlgorithmException e)
        {
            //NQLog.e("getFileSha1->NoSuchAlgorithmException###", e.toString());
            e.printStackTrace();
        } catch (OutOfMemoryError e)
        {

            // NQLog.e("getFileSha1->OutOfMemoryError###", e.toString());
            e.printStackTrace();
            throw e;
        } finally
        {
            in.close();
        }
        return null;
    }*/
}
